﻿using System.Management;
using System.Security.Cryptography;
using System.Text;

namespace ComputerInfo
{
    public class DeviceUniqueID
    {
        public static string GenerateUniqueDeviceIdentifier()
        {
            StringBuilder identifierBuilder = new StringBuilder();

            // 获取CPU序列号
            string cpuSerial = GetCpuSerialNumber();
            identifierBuilder.Append(cpuSerial);

            // 获取主板序列号
            string baseBoardSerial = GetBaseBoardSerialNumber();
            identifierBuilder.Append(baseBoardSerial);

            // 获取磁盘序列号
            string diskSerial = GetDiskSerialNumber();
            identifierBuilder.Append(diskSerial);

            // 使用SHA256对组合的字符串进行哈希处理，确保标识符长度固定
            using (SHA256 sha256Hash = SHA256.Create())
            {
                byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(identifierBuilder.ToString()));
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < bytes.Length; i++)
                {
                    builder.Append(bytes[i].ToString("x2"));
                }
                return builder.ToString();
            }
        }

        private static string GetCpuSerialNumber()
        {
            var cpuInfo = new ManagementObjectSearcher("SELECT ProcessorId FROM Win32_Processor").Get().Cast<ManagementObject>().FirstOrDefault();
            return cpuInfo != null ? cpuInfo["ProcessorId"].ToString() : string.Empty;
        }

        private static string GetBaseBoardSerialNumber()
        {
            var baseBoardInfo = new ManagementObjectSearcher("SELECT SerialNumber FROM Win32_BaseBoard").Get().Cast<ManagementObject>().FirstOrDefault();
            return baseBoardInfo != null ? baseBoardInfo["SerialNumber"].ToString() : string.Empty;
        }

        private static string GetFirstMacAddress()
        {
            var networkAdapters = new ManagementObjectSearcher("SELECT MACAddress FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'").Get();
            return networkAdapters.Cast<ManagementObject>().Select(adapter => adapter["MACAddress"].ToString()).FirstOrDefault();
        }

        private static string GetDiskSerialNumber()
        {
            var diskInfo = new ManagementObjectSearcher("SELECT SerialNumber FROM Win32_DiskDrive").Get().Cast<ManagementObject>().FirstOrDefault();
            return diskInfo != null ? diskInfo["SerialNumber"].ToString() : string.Empty;
        }
    }
}
